<template>
  <van-skeleton v-show="state.loading" :row="3" />
  <div v-show="!state.loading" class="history-week">
    <!-- 时间区域筛选 -->
    <div class="date-range">
      <div @click="adjustWeek(-7)">
        <SvgIcon
          svg-name="arrow-left"
          color="var(--sub-title-color)"
          class-name="arrow-svg-date"
        />
      </div>
      <div class="time">{{ state.currentWeek }}</div>
      <div @click="adjustWeek(7)">
        <SvgIcon
          svg-name="arrow"
          color="var(--sub-title-color)"
          class-name="arrow-svg-date"
        />
      </div>
    </div>
    <!-- 统计图 -->
    <BarEchart :dataX="state.barDataX" :dataY="state.barDataY" />

    <!-- 数据统计 -->
    <div class="title">数据统计</div>
    <DataStatistics
      type="周"
      :total="state.totalDuation"
      :average="state.averageDuration"
      :counts="state.counts"
    />

    <!-- 刷牙得分参考范围 -->
    <div class="title">刷牙得分参考范围</div>
    <ScoreLevel />
  </div>
</template>

<script setup>
import DataStatistics from './DataStatistics.vue'
import ScoreLevel from './ScoreLevel.vue'
import BarEchart from './BarEchart.vue'

import { reactive, onMounted, watch, defineProps, onBeforeUnmount } from 'vue'
import { getCurrentWeek, getNWeek } from '@/utils/util'
import { deviceId } from '@/utils/enum'
import { useRoute } from 'vue-router'
const route = useRoute()

const props = defineProps({})

watch(
  () => route.query,
  (to, from) => {
    // 在这里处理路由变化的逻辑
    if (to.random) {
      state.startDate = getCurrentWeek(new Date())[0]
      state.endDate = getCurrentWeek(new Date())[1]
      const date = getNWeek(state.startDate, state.endDate, 0)
      state.currentWeek = getWeekStr(date)
      getHistoryParam(state.startDate, state.endDate)
      clearInterval(state.timer)
      intervalEvent(state.startDate, state.endDate)
    } else {
      clearInterval(state.timer)
    }
  },
  {
    deep: true
  }
)

const state = reactive({
  barDataX: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
  // barDataY: [10, 52, 98, 70, 60, 90, 88],
  barDataY: [0, 0, 0, 0, 0, 0, 0],
  startDate: undefined,
  endDate: undefined,
  currentWeek: '',
  totalDuation: 0,
  averageDuration: 0,
  counts: 0,
  loading: true,
  timer: undefined
})

const getWeekStr = week => {
  const str1 = `${week[0].getFullYear()}年${
    week[0].getMonth() + 1
  }月${week[0].getDate()}日`
  const str2 = `${week[1].getFullYear()}年${
    week[1].getMonth() + 1
  }月${week[1].getDate()}日`
  return `${str1} - ${str2}`
}

// 获取刷牙的历史记录
const getHistoryParam = (startDate, endDate) => {
  const start = new Date(
    startDate.getFullYear(),
    startDate.getMonth(),
    startDate.getDate()
  ).getTime()
  const end = new Date(
    endDate.getFullYear(),
    endDate.getMonth(),
    endDate.getDate()
  ).getTime()

  const _D = new Date(start)
  let allDates = []
  for (let i = 0; i < 7; i++) {
    const date = new Date(_D) // 创建一个副本，用于计算每一天的日期
    date.setDate(date.getDate() + i) // 计算每一天的日期
    Hejia.getHistoryParam(
      {
        // deviceId,
        paramName: ['brushRecord'],
        startDate: date.getTime(),
        endDate: date.getTime() + 86400000
      },
      function (arr) {
        if (arr.length) {
          arr = arr.filter((item, index, self) => {
            const itemVal = item.params[0].value
            return (
              index ===
              self.findIndex(obj => {
                const arrVal = obj.params[0].value
                return itemVal === arrVal
              })
            )
          })

          // 筛选刷牙有效时间
          arr = arr.filter(item => {
            const { value } = item.params[0]
            const duration = parseInt(value.substring(10, 14), 16)
            if (duration >= 30) {
              return item
            }
          })

          const sumArr = arr.map(item => {
            const { value } = item.params[0]
            const time = parseInt(value.substring(0, 8), 16)
            const score = parseInt(value.substring(8, 10), 16)
            return score
          })

          const sum = sumArr.reduce(
            (accumulator, currentValue) => accumulator + currentValue,
            0
          )

          const average = Math.ceil(sum / sumArr.length)

          state.barDataY[i] = average
        } else {
          state.barDataY[i] = 0
        }
        state.loading = false
      },
      function (msg, obj) {
        console.log(obj.resultCode + obj.resultCodeMessage)
      }
    )
    allDates.push(date.getDate()) // 将计算得到的日期添加到数组中
  }

  // 处理数据统计
  Hejia.getHistoryParam(
    {
      // deviceId,
      paramName: ['brushRecord'],
      startDate: start,
      endDate: end + 86400000
    },
    function (arr) {
      state.totalDuation = 0

      if (arr.length) {
        arr = arr.filter((item, index, self) => {
          const itemVal = item.params[0].value
          return (
            index ===
            self.findIndex(obj => {
              const arrVal = obj.params[0].value
              return itemVal === arrVal
            })
          )
        })
        arr = arr.filter(item => {
          const { value } = item.params[0]
          const duration = parseInt(value.substring(10, 14), 16)
          if (duration >= 30) {
            return item
          }
        })

        const sum = arr.map(item => {
          const { value } = item.params[0]
          const time = parseInt(value.substring(0, 8), 16)
          const score = parseInt(value.substring(8, 10), 16)
          const duration = parseInt(value.substring(10, 14), 16)
          state.totalDuation += duration
          return score
        })
        state.totalDuation = (state.totalDuation / 60).toFixed(1)
        state.counts = arr.length
        state.averageDuration = (state.totalDuation / state.counts).toFixed(1)
      } else {
        state.totalDuation = 0
        state.averageDuration = 0
        state.counts = 0
      }
    },
    function (msg, obj) {
      console.log(obj.resultCode + obj.resultCodeMessage)
    }
  )
}
const intervalEvent = (start, end) => {
  clearInterval(state.timer)
  state.timer = setInterval(() => {
    // state.startDate = getCurrentWeek(new Date())[0]
    // state.endDate = getCurrentWeek(new Date())[1]
    // getHistoryParam(state.startDate, state.endDate)
    getHistoryParam(start, end)
  }, 1000 * 3)
}

const adjustWeek = n => {
  const date = getNWeek(state.startDate, state.endDate, n)
  state.currentWeek = getWeekStr(date)
  state.startDate = date[0]
  state.endDate = date[1]

  clearInterval(state.timer)

  getHistoryParam(state.startDate, state.endDate)
  intervalEvent(state.startDate, state.endDate)
}

onMounted(() => {
  state.startDate = getCurrentWeek(new Date())[0]
  state.endDate = getCurrentWeek(new Date())[1]
  const date = getNWeek(state.startDate, state.endDate, 0)
  state.currentWeek = getWeekStr(date)
  getHistoryParam(state.startDate, state.endDate)
  clearInterval(state.timer)
  intervalEvent(state.startDate, state.endDate)
})

onBeforeUnmount(() => {
  clearInterval(state.timer)
})
</script>

<style lang="less">
.history-week {
  .van-skeleton-paragraph,
  .van-skeleton-title {
    background-color: #ccc !important;
  }
  .date-range {
    display: flex;
    align-items: center;
    padding: 0 12px;

    .time {
      flex: 1;
      font-size: 28px;
      color: var(--title-color);
      font-weight: bold;
      text-align: center;
    }
  }

  & > .title {
    font-size: 24px;
    font-weight: 500;
    color: var(--title-color);
    margin-top: 30px;
    margin-bottom: 20px;
  }
}
</style>
